<template>
	<oauth-loading oauthIcon="wechat"></oauth-loading>
</template>

<script>
import Route from '@/utils/Route.js';
import Tools from '@/utils/Tools.js';
import oauthLoading from '@/components/oauth/loading.vue';
export default {
	components: { oauthLoading },
	data() {
		return {
			options: {},
			code: '',
			oauth: {},
			authed: false
		};
	},
	onLoad(options) {
		this.options = options;
		this.code = options.code;
		const oauth = uni.getStorageSync('oauth');
		this.oauth = oauth;
		this.codeToAuthId();
	},
	methods: {
		//
		codeToAuthId() {
			this.$get(
				this.$api.loginWithWechatCode,
				{ code: this.code, referee_id: this.oauth.referee_id || '' },
				res => {
					const bindStatus = res.data.code;
					const authId = res.data.id;
					const referee_id = res.data.referee_id;
					uni.setStorageSync('authId', authId);
					switch (this.oauth.type) {
						case 'login':
							this.wechathForLogin(authId, bindStatus, referee_id);
							break;
						case 'home':
							this.wechathToHome(authId);
							break;
						default:
							this.wechathToHome(authId);
							break;
					}
					console.log(res);
				},
				null,
				() => {
					this.authed = true;
				}
			);
		},
		wechathToHome(authId) {
			// Route.reLaunch();
			Tools.redirectToCurrentPage()
		},
		// 微信授权
		wechathForLogin(authId, bindStatus = 0, referee_id = '') {
			if (bindStatus == 1) {
				this.$get(
					this.$api.loginByThirdId,
					{ login_type: 'wechat', id: authId },
					res => {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('user_id', res.data.userInfo.user_id);
						uni.setStorageSync('referee_id', res.data.userInfo.code);
						Route.reLaunch();
					},
					null,
					() => {
						this.authed = true;
					}
				);
			} else {
				Route.redirectTo({ url: '/pages/login/index?next=1&authId=' + authId + '&referee_id=' + referee_id });
			}
		}
	}
};
</script>

<style>

</style>
